package com.arvato.common.task;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import com.arvato.common.https.HttpUtil;
import com.arvato.common.util.ContantFinalUtil;
import com.arvato.common.util.JsonUtil;
import com.arvato.common.util.MD5Util;
import com.arvato.wxwork.bean.bean_do.ncc.WxworkTaskDo;
import com.arvato.wxwork.service.ncc.WxworkTaskService;

@Component
public class WxWorkTask {

	@Autowired
	private WxworkTaskService wxworkTaskService;

	private Logger logger = LoggerFactory.getLogger(WxWorkTask.class);

	@Autowired
	private JsonUtil jsonUtil;

	/**
	 * 每天凌晨零点十分同步数据
	 */      
	@Scheduled(cron = "0 10 0 * * ? ")
	public void taskMemberInfo() {
		String dateStr = "2018/07/02";
				//new SimpleDateFormat("yyyy/MM/dd").format(new Date());
		Integer totalRecord5156 = getTotalRecord("5156",dateStr);
		int totalPageNum5156 = (totalRecord5156 + 20 - 1) / 20;
		for (int i = 1; i <= totalPageNum5156; i++) {
			memberTask(i,dateStr);
		}
		Integer totalRecord5157 = getTotalRecord("5157",dateStr);
		int totalPageNum5157 = (totalRecord5157 + 20 - 1) / 20;
		for (int i = 1; i <= totalPageNum5157; i++) {
			memberTask(i,dateStr);
		}
	}

	private Integer getTotalRecord(String campaignID, String dateStr) {
		Map<String, Object> paramMap = new HashMap<String, Object>();
		String pageSize = "20";
		paramMap.put("Date", dateStr);
		paramMap.put("CampaignID", campaignID);
		paramMap.put("PageIndex", "1");
		paramMap.put("PageSize", pageSize);
		String url = ContantFinalUtil.URL+ContantFinalUtil.CONTEXT+"/admin/wxwork/ncc/task/async";
		String token = MD5Util.md5("NccAsync#ad2*8jfdsas(^@");
		paramMap.put("token", token);
		/*
		 * logger.info("NccAsync" + ":" + url + "请求参数:" +
		 * jsonUtil.obj2String(paramMap));
		 */ 
		long startTime = System.currentTimeMillis();
		String responseStr = HttpUtil.doPostJsonData(url, paramMap);
		long endTime = System.currentTimeMillis();
		logger.info("NccAsync" + "时间:" + (endTime - startTime));
		/* logger.info("NccAsync" + "请求结果:" + responseStr); */
		Map<String, Object> resultMap = jsonUtil.str2Map(responseStr);
		Map<String, Object> map = (Map<String, Object>) resultMap.get("data");
		Map<String, Object> mapData = (Map<String, Object>) map.get("Data");
		Integer mapTotal = (Integer) mapData.get("total");
		return mapTotal;
	}

	private void memberTask(Integer pageIndex,String dateStr) {
		Map<String, Object> paramMap = new HashMap<String, Object>();
		String campaignID = "5157";
		String pageSize = "20";
		paramMap.put("Date", dateStr);
		paramMap.put("CampaignID", campaignID);
		paramMap.put("PageIndex", pageIndex);
		paramMap.put("PageSize", pageSize);
		String url = "http://localhost:8080/arvato_local_dyq/admin/wxwork/ncc/task/async";
		String token = MD5Util.md5("NccAsync#ad2*8jfdsas(^@");
		paramMap.put("token", token);
		logger.info("NccAsync" + ":" + url + "请求参数:" + jsonUtil.obj2String(paramMap));
		long startTime = System.currentTimeMillis();
		String responseStr = HttpUtil.doPostJsonData(url, paramMap);
		long endTime = System.currentTimeMillis();
		logger.info("NccAsync" + "时间:" + (endTime - startTime));
		logger.info("NccAsync" + "请求结果:" + responseStr);
		Map<String, Object> resultMap = jsonUtil.str2Map(responseStr);
		try {
			Map<String, Object> map = (Map<String, Object>) resultMap.get("data");
			Map<String, Object> mapData = (Map<String, Object>) map.get("Data");
			ArrayList<Map<String, Object>> itemList = (ArrayList<Map<String, Object>>) mapData.get("item");
			for (int i = 0; i < itemList.size(); i++) {
				String id = itemList.get(i).get("CID").toString() + itemList.get(i).get("CAMPAIGNID").toString()
						+ itemList.get(i).get("QUERYID").toString();
				WxworkTaskDo wxWorkTask = wxworkTaskService.getTaskById(id);
				if (null == wxWorkTask) {
					WxworkTaskDo dto = new WxworkTaskDo();
					if (itemList.get(i).get("UnionId") != null) {
						dto.setUnionId(itemList.get(i).get("UnionId").toString());
						dto.setId(itemList.get(i).get("CID").toString() + itemList.get(i).get("CAMPAIGNID").toString()
								+ itemList.get(i).get("QUERYID").toString());
						dto.setMobile(itemList.get(i).get("MOBILE").toString());
						dto.setCampaignId(itemList.get(i).get("CAMPAIGNID").toString());
						dto.setCid(itemList.get(i).get("CID").toString());
						dto.setCreateTime(new Date());
						dto.setStatus("0");
						if (itemList.get(i).get("QUERYID") != null) {
							dto.setQueryId(itemList.get(i).get("QUERYID").toString());
						}
						if (itemList.get(i).get("DTYPE") != null) {
							dto.setdType(itemList.get(i).get("DTYPE").toString());
						}
						wxworkTaskService.insert(dto);
					}
				}
			}
		} catch (Exception e) {
			logger.error("调用memberTask接口，数据解析出错。");
		}
	}
}